package cn.hiapi.shop.api;

import cn.hiapi.basic.ResponseEntity;
import cn.hiapi.basic.controller.BasicCurdController;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.pay.consts.PayConst;
import cn.hiapi.basic.security.TokenGet;
import cn.hiapi.basic.service.BasicService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.config.IConfigService;
import cn.hiapi.interfaces.finance.IPaymentService;
import cn.hiapi.interfaces.finance.model.PayTypes;
import cn.hiapi.interfaces.finance.model.RechargeModel;
import cn.hiapi.shop.query.ActivityLotteryAdQuery;
import cn.hiapi.shop.service.shop.ShopLinkUserService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivityLotteryAd;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.service.activity.ActivityLotteryAdService;
import cn.hiapi.shopkeeper.service.order.ActivityLotteryOrderService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import cn.hiapi.shopkeeper.service.shopkeeper.ActivityPreviewService;
import cn.hiapi.shopkeeper.service.shopkeeper.ShopUserService;
import cn.hiapi.utils.DateUtils;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2023/2/4 16:27
 */
@RestController
@RequestMapping("/shop/activity-ad")
public class ActivityAdController extends BasicCurdController<ActivityLotteryAd, Long, ActivityLotteryAd, ActivityLotteryAdQuery> {

    public ActivityAdController(ActivityLotteryAdService basicService, DispatchContext dispatchContext) {
        super(basicService, dispatchContext);
    }

    @Override
    public ActivityLotteryAd parseData(ActivityLotteryAd data) {
        return null;
    }


    @Override
    public ActivityLotteryAdQuery setQuery(ActivityLotteryAdQuery query) {
        Token<Object> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), query.getShopId());
        return super.setQuery(query);
    }

    @Override
    public List<ActivityLotteryAd> toListVo(List<ActivityLotteryAd> list, String[] fields) {
        return list;
    }

    @Override
    public ActivityLotteryAd toData(ActivityLotteryAd data, String[] fields) {
        return data;
    }


    @ApiOperation(value = "提交广告发布", notes = "提交广告发布", nickname = "AdinZ")
    @PostMapping("/submit")
    @Transactional
    public ResponseEntity submitAd(@RequestBody ActivityLotteryAd data,
                                   @RequestParam(value = "payType", required = false, defaultValue = "weixin") String type) {
        if (StringUtils.isEmpty(data.getTitle()))
            return toError("奖品名字错误");
        if (StringUtils.isEmpty(data.getThumb())) {
            return toError("请上传奖品图片");
        }
        if (data.getShopId() <= 0) return toError("缺少参数 shopId");
        if (data.getStartTime() < 1000000)
            throw new BasicException("活动开始时间错误");
        if (data.getEndTime() < 100000)
            throw new BasicException("活动结束时间错误");
        if (data.getUseStart() < 100000 || data.getUseEnd() < 10000)
            throw new BasicException("兑换时间错误");
        try {
            Date dayStart = DateUtils.parse(DateUtils.format(DateUtils.FORMAT_YYYY_MM_DD) + " " + data.getDayStart(), DateUtils.FORMAT_YYYY_MM_DD_HH_MM);
            Date dayEnd = DateUtils.parse(DateUtils.format(DateUtils.FORMAT_YYYY_MM_DD) + " " + data.getDayEnd(), DateUtils.FORMAT_YYYY_MM_DD_HH_MM);

            if (dayEnd.getTime() < dayStart.getTime()) {
                dayEnd = DateUtils.addDay(dayEnd, 1);
            }
            double v = ((double) (dayEnd.getTime() - dayStart.getTime())) / (60d * 60 * 1000);
            double ceil = Math.ceil(v);
            data.setTimeNum((int) ceil);


        } catch (Exception e) {
            return toError("时间格式错误");
        }


        Token<Object> token = TokenGet.get();
        JSONObject config = this.dispatchContext.getServiceOne(IConfigService.class).getConfig(token.getMerchantId(), AppConst.CONFIG_SHOPKEEPER_ACTIVITY);
        final BigDecimal price = JsonUtils.getBigDecimal(config, AppConst.CONFIG_SHOPKEEPER_ACTIVITY_LOTTERY_AD_PRICE);
        if (price.compareTo(BigDecimal.ZERO) < 0) return toError("系统设置价格错误");
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), data.getShopId());
        data.setStatus(0);
        data.setFeePrice(price);
        data.setPayMoney(price.multiply(BigDecimal.valueOf(data.getTimeNum())));
        this.dispatchContext.getServiceOne(ActivityLotteryAdService.class).save(data);
        Map map = this.dispatchContext.getServiceOne(IPaymentService.class).createPayment(RechargeModel.builder()
                .payType("shopkeeper_shop_wx_pay:" + PayConst.WXPAY_PROGRAM)
                .type(ActivityType.LOTTERY_AD.name())
                .title(data.getTitle())
                .actual(data.getPayMoney()).money(data.getPayMoney())
                .fid(data.getId())
                .fidType("SHOP")
                .uid(token.getFid())
                .build(), PayTypes.WXPAY_MINI);
        return toSuccess(map);
    }

    @ApiOperation(value = "统计数据", notes = "统计数据", nickname = "AdinZ")
    @GetMapping("/data-view")
    public ResponseEntity data(@RequestParam("shopId") long shopId, @RequestParam("id") long id) {

        Token<Object> token = TokenGet.get();
        this.dispatchContext.getServiceOne(ShopLinkUserService.class).verifyShop(token.getFid(), shopId);

        JsonUtils.Builder builder = JsonUtils.builder();
        long order = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(new QueryWrapper().eq("aid", id));
        builder.put("order", order); //订单总数
        long lottery = this.dispatchContext.getServiceOne(ActivityLotteryOrderService.class).count(
                new QueryWrapper().eq("aid", id)
                        .eq("lotteryState",1)
        );
        builder.put("totalLottery", lottery); //抽奖参与人数
        return toSuccess(builder.build());

    }
}
